import { ProTable, ActionType } from '@ant-design/pro-components';
import React, { useEffect, useRef, useState } from 'react';
import { message, Space, Button, Modal } from 'antd';
import { useRequest } from 'ahooks';
import Add from "./component/Add";
import { evaluationComposeV1ControllerDestroy, evaluationComposeV1ControllerIndex } from "@/services/auto/evaluationCompose";
import { css } from "@emotion/react";
import ScrollPageList, { PageListRef } from "@/components/ScrollPageList";
import { articleV1ControllerIndexNormal } from "@/services/auto/article";
import { Link } from "@umijs/max";
import { GetScrollPageParam } from "common/interface";
import AddDiffBtn from "@/components/AddDiffBtn";

export default () => {
  const [searchParam, setSearchParam] = useState<{ keyword?: string }>();

  const { runAsync: deleteRun } = useRequest(evaluationComposeV1ControllerDestroy, {
    manual: true,
    onSuccess: () => {
      message.success('删除成功');
      scrollPageListRef.current?.refresh();
    },
  });

  const scrollPageListRef = useRef<PageListRef<API.EvaluationComposeIndexResult>>(null);

  const [list ,setList] = useState<API.EvaluationComposeIndexResult[]>();

  const [count, setCount] = useState<number>();

  const [loading, setLoading] = useState<boolean>();

  const [showPageScroll, setShowPageScroll] = useState<boolean>(false);

  useEffect(() => {
    setShowPageScroll(true);
  }, []);

  const elementRef = useRef<HTMLDivElement>(null);

  return (
    <div ref={elementRef} className="h-full" css={css`
      .ant-pro-table, .ant-pro-card, .ant-pro-card-body{
        height: 100% !important;
      }
      
      .ant-table-wrapper {
        height: calc(100% - 64px);
        
        .ant-spin-nested-loading, .ant-spin-container, .ant-table, .ant-table-container{
          height: 100%;
        }
        
        .ant-table-body{
          height: calc(100% - 47px);
        }
      }
    
    `}>
      <ProTable<API.EvaluationComposeIndexResult>
        loading={loading}
        rowKey="uuid"
        scroll={{y: '100%', scrollToFirstRowOnChange: true}}
        search={false}
        dataSource={list}
        pagination={false}
        toolbar={{
          settings: [],
          search: {
            onSearch: (value: string) => {
              setSearchParam({ keyword: value || undefined });
              scrollPageListRef.current?.scrollToTop();
            },
          },
          actions: [
            <span key="count">共计 {count ?? '-'} 条</span>,
            <Add key="add" reload={()=>{
              scrollPageListRef.current?.refresh();
            }}>
              <Button
                type="primary"
              >
                添加
              </Button>
            </Add>
            ,
          ],
        }}
        columns={[
          {
            title: '序号',
            key: 'index',
            width: 80,
            valueType: 'index',
          },
          {
            title: '名称',
            dataIndex: 'title',
          },
          {
            title: '耳机数据源',
            key: 'earbudsEvaluation',
            render: (_, record)=>{
              return <>
                <div>{record.earbudsEvaluation.title}</div>
                （{record.earbudsEvaluationDataGroup}）
              </>
            }
          },
          {
            title: '音源数据源',
            key: 'soundSourceEvaluation',
            render: (_, record)=>{
              return record.soundSourceEvaluation ? <>
                <div>{record.soundSourceEvaluation?.title}</div>
                （{record.soundSourceEvaluationDataGroup}）
              </> : '-'
            }
          },
          {
            title: '添加/修改时间',
            dataIndex: 'updateTime',
            valueType: 'dateTime',
            width: 150
          },
          {
            align: 'center',
            title: '操作',
            key: 'option',
            valueType: 'option',
            width: 120,
            render: (_, record) => {
              return (
                <Space direction="vertical" size={0}>
                  <Link to={{
                    pathname: `/evaluation-compose/${record.uuid}`
                  }} target="_blank">
                    <Button type="link">
                      查看
                    </Button>
                  </Link>
                  <AddDiffBtn evaluationComposeUuid={record.uuid} badgeProps={{
                    offset: [-15,8]
                  }}>
                    <Button type="link">
                      添加对比
                    </Button>
                  </AddDiffBtn>
                  <Add data={record} reload={()=>{
                    scrollPageListRef.current?.refresh();
                  }}>
                    <Button type="link">
                      编辑
                    </Button>
                  </Add>
                  <Button type="link" danger onClick={()=>{
                    Modal.confirm({
                      title: '删除后不可恢复，确定删除当前HiFi系统？',
                      onOk: ()=>{
                        return deleteRun({uuid: record.uuid});
                      }
                    })
                  }}>
                    删除
                  </Button>
                </Space>
              );
            },
          },
        ]}
      />
      {
        showPageScroll && <ScrollPageList<GetScrollPageParam<API.EvaluationComposeV1ControllerIndexParams>, API.EvaluationComposeIndexResult>
          ref={scrollPageListRef}
          param={searchParam}
          service={evaluationComposeV1ControllerIndex}
          order={{
            orderBy: 'updateTime',
            direction: 'DESC',
          }} getScrollableTarget={() => elementRef.current?.querySelector('.ant-table-body')!} onListChange={(l, c) => {
            setList(l);
            setCount(c);
        }} onLoadingChange={(l) => {
          setLoading(l);
        }}/>}
    </div>
  );
};
